package com.idanchuang.component.logback.web.filter;

import com.alibaba.ttl.TransmittableThreadLocal;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 记录请求执行时间
 */
@WebFilter(urlPatterns = "/*", asyncSupported = true)
public class RequestStartTimeFilter implements Filter {

    /**
     * 处理时间 线程绑定
     */
    public static final ThreadLocal<String> REQUEST_URL_THREAD_LOCAL = new TransmittableThreadLocal<>();
    public static final ThreadLocal<Long> REQUEST_START_THREAD_LOCAL = new TransmittableThreadLocal<>();

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        REQUEST_START_THREAD_LOCAL.set(System.currentTimeMillis());
        REQUEST_URL_THREAD_LOCAL.set(request.getRequestURL().toString());
        try {
            chain.doFilter(request, response);
        } finally {
            REQUEST_START_THREAD_LOCAL.remove();
            REQUEST_URL_THREAD_LOCAL.remove();
        }
    }

}
